const express = require('express');
const router = express.Router();
const experimentController = require('../../controllers/experiment.controller');
const auth = require('../../middlewares/auth');
const role = require('../../config/roles');
//const validate = require('../../middlewares/validate');
//const experimentValidation = require('../../validations/experiment.validation');

// 获取实验列表（需要学生权限）
router.get(
  '/experiments',
  auth(role.STUDENT),
  async (req, res, next) => {
    try {
      // 使用 req.user.id 而不是 req.user.studentId
      const studentId = req.user.id;
      console.log(`获取实验列表请求，学生ID: ${studentId}`);

      // 获取实验列表和学生数据
      const experiments = await experimentController.getAllExperiments(req, res);
      console.log(`获取到的实验列表: ${JSON.stringify(experiments)}`);
      const studentExperimentData = await experimentController.getStudentExperimentData(studentId);

      // 组合响应数据
      const responseData = experiments.map(exp => {
        const studentData = studentExperimentData.find(data => data.experimentId === exp.id) || {};
        return {
          id: exp.id,
          name: exp.title,
          description: exp.description,
          estimatedTime: exp.estimatedTime,
          deadline: studentData.deadline,
          status: studentData.status || 'pending',
          progress: studentData.progress || 0,
          grade: studentData.grade || null,
          link: `/public/experiments/${exp.id}.html`,
          resources: exp.resources
        };
      });

      res.json({
        success: true,
        experiments: responseData
      });
    } catch (err) {
      next(err);
    }
  }
);

// 下载实验材料
router.get(
  '/experiments/:experimentId/resources/:resourceId/download',
  (req, res, next) => {
    auth(role.STUDENT),
    console.log(`下载资源请求，实验ID: ${req.params.experimentId}, 资源ID: ${req.params.resourceId}`);
    experimentController.downloadResource(req, res, next);
  }
);

// // 获取实验详情
// router.get(
//   '/experiments/:experimentId',
//   auth(role.STUDENT),
//   //validate(experimentValidation.getExperiment),
//   experimentController.getExperimentDetails
// );

module.exports = router;